package tc.map;

import java.util.LinkedList;
import java.util.Iterator;

import javax.swing.SwingUtilities;

/**Mediates the main thread with TcMviewTilesDispatch, which is running in separate thread.
All functions of this mediator are thread save. 
*/
public class TcTileLoaderMediator {
	
	private final LinkedList<TcTile> dirtyTiles;
	private TcTileAddress center;
	private RepaintView repainter;
		
	TcTileLoaderMediator (TcMview view) {
		dirtyTiles = new LinkedList<TcTile>();
		this.center = new TcTileAddress(1,1,1); 
		this.repainter = new RepaintView(view);
	}
	
	/** Appends dirty tile to load.
    */
	public synchronized void appendTile(TcTile tile) {
		dirtyTiles.addFirst(tile);
	}
	
	/** Takes next tile to process. Tile is removed from the buffer.
    */
	public synchronized TcTile nextTileToProcess()	{
		if (dirtyTiles.size() == 0) { return null; }
		
		Iterator<TcTile> ti = dirtyTiles.iterator();
	
		TcTile tile = ti.next();
	
		while (ti.hasNext())
		{	TcTile tilei = ti.next();
			if ( tilei.getAddress().distanceTo(center) > tile.getAddress().distanceTo(center) ) continue;
			tile = tilei;
		}

		dirtyTiles.remove(tile);
		
		return tile;
	}
	
	/**Dirty tiles count getter.
    */
	public synchronized int dirtyTilesSize() {
		return dirtyTiles.size();
	}
	
	/**Sets current center tile.
    */
	public synchronized void updateCenter(TcTileAddress center) {
		this.center = center;
	}
	
	/**Updates view.
	*/
	public synchronized void updateView() {
		SwingUtilities.invokeLater(repainter);
	}
	
	/**Hides view from other functions in this class. View is acessed indirectly.
	*/
	private class RepaintView implements Runnable {
		private final TcMview view;
		
		public RepaintView(TcMview view) {
			this.view = view;
		}
		
		public void run() {
			view.repaint();
		}
	}
}
